
from flask import Flask,render_template,request,redirect,url_for,session
from flask import jsonify
import json
import uuid
from werkzeug.utils import secure_filename
import os
from sqlalchemy import func

from datetime import timedelta
from flask_cors import * 
import config
import os
from exts import db
from models import *
app = Flask(__name__)
cors = CORS(app)
app.config['JSON_AS_ASCII'] = False
app.config.from_object(config)
db.init_app(app)


@app.route('/login/',methods=['GET','POST'], strict_slashes=False)
#登陆路由
def login():
        if request.method == 'GET':
            return jsonify({'status': '300', 'errmsg': '不允许范围'})
        else:
            data = json.loads(request.get_data(as_text=True),strict=False)     
               
            userid = data["userid"]
            users = User.query.filter(User.userid == userid).first()
            
            #单个first用户转json
            if users:
                User.query.filter_by(userid=userid).update({'address':data["address"],"phone":data["phone"]})
                db.session.commit()
                # print(users.to_json())
                users = User.query.filter(User.userid == userid).first()
                return  jsonify({'status': '200', 'errmsg': "用户信息更新成功","data":users.to_json()})
            else:
                ###用户不存在
                user = User(uuid=str(uuid.uuid1()),userid = data["userid"],username=data["username"],avatar=data["avatar"],address=data["address"],phone=data["phone"])
                db.session.add(user)
                ###排查排查插入问题 注册插入数据报错(id must Intgeter)
                db.session.commit()
                return jsonify({'status': '200', 'errmsg': "新增成功"})




@app.route('/giftlist/',methods=['GET','POST'], strict_slashes=False)
#获取礼品路由
def giftlist():
    if request.method == 'GET':
        # data = json.loads(request.get_data(as_text=True))  
        activid= request.args.get("activid")
        print(activid)
        gifts = Gift.query.filter(Gift.activid == activid).all()
       #多条数据转json
        result = []
        for gift in gifts:
            result.append(gift.to_json())
        # print(result)
        
        return jsonify({ "code": 0, "count": 1000, "data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

       

# @app.route('/addgift/',methods=['GET','POST'], strict_slashes=False)
# #添加礼品路由
# def addgift():
#     if request.method == 'POST':
#         activid=request.form['activid']
#         winname=request.form['winname']
#         giftnum=request.form['giftnum']
#         giftname=request.form['giftname']
#         gifts = Gift(activid = activid,giftnum=giftnum,giftname=giftname,giftid=str(uuid.uuid1()),winname=winname)
#         db.session.add(gifts)
#                 ###排查排查插入问题 注册插入数据报错(id must Intgeter)
#         db.session.commit()
#         return jsonify({'status': '200', 'errmsg': "新增成功"})
#     else:
#         return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/getuseractive/',methods=['GET','POST'], strict_slashes=False)
#获取用户参加活动路由
def getuseractive():
    if request.method == 'POST':
        data = json.loads(request.get_data(as_text=True))  
        userid = data["userid"]
        tickets = Ticket.query.filter(Ticket.userid == userid).group_by(Ticket.activid).all()
        result = []
        for ticket in tickets:
            result.append(ticket.to_json())
        return jsonify({'status': '200', 'errmsg': "返回成功","data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/win/',methods=['GET','POST'], strict_slashes=False)
#获取某个人中奖记录
def win():
    if request.method == 'POST':
        
        data = json.loads(request.get_data(as_text=True))  
        userid = data["userid"]
        activid = data["activid"]
        tickets = Ticket.query.filter(Ticket.userid == userid,Ticket.iswin == "1",Ticket.activid == activid).all()
        result = []
        for ticket in tickets:
            result.append(ticket.to_json())
        # print(result)
        return jsonify({'status': '200', 'errmsg': "返回成功","data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/addactive/',methods=['GET','POST'], strict_slashes=False)
#获取某个人中奖记录
def addactive():
    if request.method == 'POST':
        # data = json.loads(request.get_data(as_text=True))  
        userid = data["userid"]
        active = Active(activid = str(uuid.uuid1()),activityname=data["activityname"],activetime=data["activetime"],sponsorid=userid,sponsorname=data["username"])
        db.session.add(active)
                ###排查排查插入问题 注册插入数据报错(id must Intgeter)
        db.session.commit()
        useractivelist = Active.query.filter(Active.sponsorid == userid).all()
       #多条数据转json
        result = []
        for activelist in useractivelist:
            result.append(activelist.to_json())
        # print(result)
        return jsonify({'status': '200', 'errmsg': "新增活动成功","data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})


@app.route('/activelist/',methods=['GET','POST'], strict_slashes=False)
@app.route('/<int:page>',methods=['GET', 'POST'])
#分页效果
#分页效果
#获取小于活动路由(未筛选小于3个小时的数据)
def activelist(page=None):
    if request.method == 'GET':
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        # actives = Active.query.filter().all()
        actives = Active.query.filter().paginate(page, limit, error_out=False)
        pagedata= actives.items
        # print(type(a))

        result = []
        for active in pagedata:
            result.append(active.to_json())
        # print(result)
        return jsonify({ "code": 0, "count": 1000, "data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/getticket/',methods=['GET','POST'], strict_slashes=False)
#查某个人购票记录
def getticket():
    if request.method == 'POST':
        data = json.loads(request.get_data(as_text=True))  
        userid = data["userid"]
        activid = data["activid"]
        tickets = Ticket.query.filter(Ticket.userid == userid,Ticket.activid == activid).all()
        result = []
        for ticket in tickets:
            result.append(ticket.to_json())
        # print(result)
        return jsonify({'status': '200', 'errmsg': "返回成功","data":result})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/addticket/',methods=['GET','POST'], strict_slashes=False)
#购票路由
def addticket():
    if request.method == 'POST':
        data = json.loads(request.get_data(as_text=True))  
        userid = data["userid"]
        activid = data["activid"]

        tickets = Ticket(activid = data["activid"],userid=data["userid"],ticketnum=str(uuid.uuid1()))
        db.session.add(tickets)
                ###排查排查插入问题 注册插入数据报错(id must Intgeter)
        db.session.commit()
        
        # result = []
        # for ticket in tickets:
        #     result.append(ticket.to_json())
        # print(result)
        return jsonify({'status': '200', 'errmsg': "添加成功"})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})
@app.route('/vue',methods=['GET','POST'], strict_slashes=False)
#购票路由
def vue():
    if request.method == 'POST':
        
        username=request.form['activename']
        print(username)

        # data = json.loads(request.get_data(as_text=True),strict=False)     
               
        # id = data["page"]
  
        # result = []
        # for ticket in tickets:
        #     result.append(ticket.to_json())
        # print(result)
        return jsonify({'status': '200', 'errmsg': "添加成功","data":username})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})


@app.route('/addactive1/',methods=['GET','POST'], strict_slashes=False)
#获取某个人中奖记录
def addactive1():
    if request.method == 'POST':
        activityname=request.form['activename']  
        activetime=request.form['enddata']  
        username= "zorelu"
        userid= "123"
        active = Active(activid = str(uuid.uuid1()),activityname=activityname,activetime=activetime,sponsorid=userid,sponsorname=username)
        db.session.add(active)
                ###排查排查插入问题 注册插入数据报错(id must Intgeter)
        db.session.commit()
       
       #多条数据转json


        # print(result)
        return jsonify({'status': '200', 'errmsg': "新增活动成功","data":"ok"})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/delactive/',methods=['GET','POST'], strict_slashes=False)
#del2
def delactive():
    if request.method == 'POST':
        activid=request.form['activid']
       
       #多条数据转json
        #print(activid)
        delactive = Active.query.filter(Active.activid == activid).first()
        # print(delactive)
        db.session.delete(delactive)
        
                ###排查排查插入问题 注册插入数据报错(id must Intgeter)
        db.session.commit()
        # print(result)
        return jsonify({'status': '200', 'errmsg': "新增活动成功","data":activid})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/getactive/',methods=['GET','POST'], strict_slashes=False)
#del2
def getactive():
    if request.method == 'POST':
        activid=request.form['activid']
       
       #多条数据转json
        # print(activid)
        getactive = Active.query.filter(Active.activid == activid).first()
        # print(getactive.to_json())
        

        
        return jsonify({'status': '200', 'errmsg': "新增活动成功",'data':getactive.to_json()})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})

@app.route('/addgift/', methods=['POST', 'GET'], strict_slashes=False)
#上传路由
def upload():
    if request.method == 'POST':
        activid=request.form['activid']
        winname=request.form['winname']
        filename=request.form['filename']
        giftnum=request.form['giftnum']
        giftname=request.form['giftname']
        print(activid)
        # f = request.files['file']
        # basepath = os.path.dirname(__file__)  # 当前文件所在路径
        # # print(activid,f.filename,winname)
        # uploadfile = basepath + '\\static\\'
        # upload_path = os.path.join( uploadfile,secure_filename(f.filename))
        # f.save(upload_path)
        # print(upload_path)
        # giftimg = Gift.query.filter(Gift.activid == activid).first()
        gifts = Gift(activid = activid,giftnum=giftnum,giftname=giftname,giftid=str(uuid.uuid1()),winname=winname,imagesurl=filename)
        db.session.add(gifts)
        db.session.commit()
        return jsonify({"code": 0, "count": 1000,'data':"ok"})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})


@app.route('/uploadtest/', methods=['POST', 'GET'], strict_slashes=False)
#上传路由
def uploadtest():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  
        print(f.filename)# 当前文件所在路径
        # print(activid,f.filename,winname)
        uploadfile = basepath + '\\static\\'
        upload_path = os.path.join( uploadfile,secure_filename(f.filename))
        f.save(upload_path)
        
        return jsonify({"code": 0, "count": 1000,'data':f.filename})
    else:
        return jsonify({'status': '300', 'errmsg': '请求错误'})
app.run(debug=True,host='0.0.0.0')